﻿using Autofac;
using System;

namespace Cyss.Core
{

    public class IOCCore : IIOCCore
    {
        /// <summary>
        /// 获取注入服务实例，只适用于注册单例服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>() where T : class
        {
            return (T)Resolve(typeof(T));
        }


        /// <summary>
        /// 获取注入服务实例，
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T ResolveNamed<T>(string serviceName) where T : class
        {
            var component = Resolve<IComponentContext>();
            return component.ResolveNamed<T>(serviceName);
        }


        public bool IsRegistered<T>() where T : class
        {
            var obj = Resolve<T>();
            return obj != null;
        }

        /// <summary>
        /// Resolve dependency
        /// </summary>
        /// <param name="type">Type of resolved service</param>
        /// <returns>Resolved service</returns>
        public object Resolve(Type type)
        {
            var sp = GetServiceProvider();
            if (sp == null)
                return null;
            return sp.GetService(type);
        }

        /// <summary>
        /// Get IServiceProvider
        /// </summary>
        /// <returns>IServiceProvider</returns>
        protected virtual IServiceProvider GetServiceProvider()
        {
            return ServiceProviderFactory.Services;
        }
    }

}
